<?php

class Itvina_Controller_Action_Helper_Common extends Zend_Controller_Action_Helper_Abstract
{
	public $pluginLoader;
	protected static $_instance = null;

	public function __construct()
	{
		$this->pluginLoader = new Zend_Loader_PluginLoader ();
	}

	public static function getInstance()
	{
		if (null === self::$_instance)
		{
			self::$_instance = new self ();
		}
		return self::$_instance;
	}

	function direct($function, $params = array())
	{
		return $function ( func_get_args () );
	}

	function getCaption($column_name)
	{
		return $this->_actionController->view->partial ( "index/manage/caption.phtml", "admin", array ("caption" => $this->_actionController->view->captions, "column" => $column_name ) );
	}

	function getDescription($column_name)
	{
		$captions = $this->_actionController->view->captions;
		$constant_code = "column-description-{$column_name}";
		$caption = $captions [$constant_code]->constant_content;
		return $caption;
	}

	function getCaptions()
	{
		return $this->_actionController->view->captions;
	}

	function replaceCaptions($array_replace = array())
	{
		if (count ( $array_replace ) == 0)
			return;
		$captions = $this->_actionController->view->captions;
		foreach ( $array_replace as $key => $value )
		{
			$$key = $value;
		}
		foreach ( $captions as $key => $caption )
		{
			$constant_content = $caption->constant_content;
			eval ( "\$constant_content=\"$constant_content\";" );
			$captions [$key]->constant_content = $constant_content;
		}
	}

	function setCaptions($array_replace = array(), $array_module_name = array())
	{
		$captions = $this->_actionController->view->captions;
		if (! isset ( $captions ))
		{
			if (count ( $array_module_name ) == 0)
				$array_module_name = array ($this->_actionController->getRequest ()->getModuleName () );
			$string_module_name = implode ( "','module-", $array_module_name );
			$constant = new Admin_Model_Constant ();
			$captions = $constant->fetchAllBase ( " constant_constant_group_code IN ('module-$string_module_name') ", null, null, null, 'constant_code' );
			$this->_actionController->view->captions = $captions;
			$this->replaceCaptions ( $array_replace, $captions );
		}
		return $captions;
	}

	public function paginate($data, $item_count_per_page = 50, $page_range = 10)
	{
		$paginator = Zend_Paginator::factory ( $data );
		$paginator->setCurrentPageNumber ( $this->_actionController->getRequest ()->getParam ( 'page' ) );
		$paginator->setItemCountPerPage ( $this->_actionController->getRequest ()->getParam ( 'limit', $item_count_per_page ) );
		$paginator->setPageRange ( $page_range );
		$this->_actionController->view->paginator = $paginator;
		return $this->_actionController->view->paginator;
	}

	public function virtualPaginate($item_total, $item_count_per_page = 50, $page_range = 10)
	{
		$data = array ();
		for($i = 0; $i < $item_total; $i ++)
			$data [] = $i;
		$paginator = Zend_Paginator::factory ( $data );
		$paginator->setCurrentPageNumber ( $this->_actionController->getRequest ()->getParam ( 'page' ) );
		$paginator->setItemCountPerPage ( $this->_actionController->getRequest ()->getParam ( 'limit', $item_count_per_page ) );
		$paginator->setPageRange ( $page_range );
		$this->_actionController->view->paginator = $paginator;
		return $this->_actionController->view->paginator;
	}

	public function getOrderArray($default = array(), $require = array())
	{
		$order = $this->_actionController->getRequest ()->getParam ( 'order', '' );
		$array = $require;
		if ($order == "")
		{
			if (count ( $default ) > 0)
				$array = array_merge ( $array, $default );
		}
		else
		{
			$string_order=str_replace ( "-", " ", $order );
			$column=str_replace(array(" DESC"," ASC"), "", $string_order);
			$array_order=array($string_order);
			if(count($array)==1 && strpos($array[0],$column)!==false)
				$array = $array_order;
			else
				$array = array_merge ( $array ,$array_order);
		}
		return $array;
	}

	public function getOrderString($default = array(), $require = array())
	{
		$pieces = $this->getOrderArray ( $default, $require );
		$string = implode ( ",", $pieces );
		$string = " ORDER BY " . $string;
		return $string;
	}

	public function alert($message = null, $url = "")
	{
		if ($message != null)
			$message = "alert('$message');";
		else
			$message = "";
		if ($url != "")
		{
			if (is_numeric ( $url ))
				$url = "history.go($url)";
			else
				$url = "window.location='$url'";
		}
		die ( "<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
		<script>$message $url</script>" );
	}

	public function redirect($message = null, $url = "", $second = 5, $continue_message = null, $auto_format = true)
	{
		$span_second = "<span id='second' style='color:red;font-weight:bold'>$second</span>";
		if ($continue_message === null)
			$continue_message = "<div style='font-size:12px;text-align:center;margin-top:10px;'>
			<a href='javascript:void();' onclick=\"$url\">Click vào đây để tiếp tục</a> (còn $span_second giây)
			</div>";
		else
			eval ( "\$continue_message=\"$continue_message\";" );
		if ($url != "")
		{
			if (is_numeric ( $url ))
				$url = "history.go($url)";
			else
				$url = "window.location='$url'";
		}
		$result = "<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
		<script>
			var second=$second;
			setTimeout('countDown()',1000);
			function countDown()
			{
				second--;
				if(second<=0)
					commonRedirect();
				else
				{
					setTimeout('countDown()',1000);
					document.getElementById('second').innerHTML=second;
				}
			}
			function commonRedirect()
			{
				$url
			}
		</script>";
		if ($auto_format)
			$result .= "<div style='width:600px;margin:auto;font-size:16px;'>";
		$result .= $message . $continue_message;
		if ($auto_format)
			$result .= "</div>";
		return $result;
	}

	public function dump($var, $label = null, $echo = true)
	{
		echo "<!-- DEBUG: ";
		Zend_Debug::dump ( $var, $label, $echo );
		echo "-->";
	}

	public function form(Zend_Form $form)
	{
		//set thuoc tinh cho form
		$form->setAttrib ( "id", "adminForm" );
		
		//them input hidden
		$form->addElement ( 'hidden', 'adminAction' );
		
		//load deco mac dinh
		$form->loadDefaultDecorators ();
		
		//lay tieu de, ghi chú form từ hằng số
		$this->getCaptions ();
		
		//xử lí cho từng element
		$no = 0;
		foreach ( $form->getElements () as $element )
		{
			//filters
			$description = $element->getDescription ();
			switch (get_class ( $element ))
			{
				case "Zend_Form_Element_Text" :
					$element->addFilters ( array ('StripTags' ) );
					$add_description = "";
					$add_class = "";
					break;
				case "Zend_Form_Element_Textarea" :
					if (strpos ( $element->class, 'editor' ) === false)
						$element->addFilters ( array ('StripTags' ) );
					$add_description = $description==""?"":"<br/><br/>";
					$add_class = "";
					break;
				case "Zend_Form_Element_Password" :
					$element->addFilters ( array ('StringTrim' ) )->addValidator ( 'StringLength', false, array (6, 25 ) );
					$add_description = "";
					$add_class = "";
					break;
				case "Zend_Form_Element_Radio" :
					$add_description = $description==""?"":"<br/><br/>";
					$add_class = "";
					break;
				case "Zend_Form_Element_Hidden" :
					$element->setDecorators ( array ('ViewHelper' ) );
					$add_description = null;
					$add_class = "";
					break;
				case "Zend_Form_Element_MultiCheckbox" :
					$add_description = $description==""?"":"<br/><br/>";
					$add_class = "";
					break;
				case "Itvina_JQuery_Form_Element_DatePicker" :
					$add_description = $this->calendar ( $element );
					$add_class = " iHasDatepicker";
					break;
				default :
					$element->addFilters ( array ('StringTrim' ) );
					$add_description = "";
					$add_class = "";
					break;
			}
			
			//xu ly phan description.
			//nếu element hidden thì không thêm vào dãy phân cách
			//ngược lại thêm vào dãy phân cách
			if ($add_description !==null)
			{
				
				$description = $add_description . $description . "</dd><dd class='clear clear" . $no . "' id='" . $element->getName () . "-bottom'>";
				$element->setDescription ( $description );
				$element->addDecorator ( 'Description', array ('escape' => false, 'tag' => '' ) );
			}
			
			//xu li cho icon dấu * khi ràng buộc dữ liệu
			if ($element->isRequired ())
			{
				$label = $element->getLabel ();
				$label .= "<div class='require'></div>";
				$element->setLabel ( $label );
				$add_class .= ' crequire';
			}
			
			//add class cho element
			$class = $element->class;
			$class .= $add_class;
			$class = trim ( $class );
			if ($class != "")
				$element->class = $class;
			$no = 1 - $no;
		}
	}

	function getRandomString($length = 6, $validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ0123456789")
	{
		$validCharNumber = strlen ( $validCharacters );
		$result = "";
		for($i = 0; $i < $length; $i ++)
		{
			$index = mt_rand ( 0, $validCharNumber - 1 );
			$result .= $validCharacters [$index];
		}
		return $result;
	}

	public function calendar(&$element)
	{
		//lấy tham số từ đối tượng datePicker
		$name = $element->getName ();
		$from_year = $element->from_year;
		$to_year = $element->to_year;
		$have_check = $element->have_check;
		$default_check = $element->default_check;
		$default_time = $element->default_time;
		$have_empty_option = $element->have_empty_option;
		$result = "";
		$controller = $this->_actionController;
		$request = $controller->getRequest ();
		$adminAction = $request->getParam ( 'adminAction', '' );
		
		//MẶC ĐỊNH GIÁ TRỊ CHO THAM SỐ
		$default_check = $default_check == "" ? 0 : $default_check;
		$default_time = $default_time == "" ? time () : $default_time;
		$have_check = $have_check == "" ? 0 : $have_check;
		$have_empty_option = $have_empty_option == "" ? 0 : $have_empty_option;
		$from_year = $from_year == "" ? date ( 'Y' ) - 3 : $from_year;
		$to_year = $to_year == "" ? date ( 'Y' ) + 3 : $to_year;
		
		//giá trị ngày tháng năm		
		$time = $request->getParam ( $name, $default_time );		
		$time = Itvina_Model_Abstract::settype ( $time, Itvina_Model_Abstract::TIME );
		$d = date ( 'd', $time );
		$m = date ( 'm', $time );
		$y = date ( 'Y', $time );
		
		//giá trị check chọn
		if ($have_check == "0")
			$c = 1;
		else
		{
			if ($adminAction == "")
				$c = $default_check;
			else
				$c = $request->getParam ( "c_$name", 0 );
		}
		
		//SET CẤU HÌNH CHO CONTROL 
		//thiết lập định dạng ngày tháng năm 
		$element->setValue ( date ( "d.m.Y", $time ) );
		//vô hiệu, kích hoạt cửa sổ chọn
		if ($c == "0")
			$element->setAttrib ( "disabled", "disabled" );
		
		//hiển thị script hỗ trợ
		$script = "
		$(document).ready(function(){ 
		
			var daynums=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		
			$('#$name')
			.datepicker({
			   onSelect: function(dateText, inst) 
			   {
				   $('#d_$name').val( inst.selectedDay);
				   $('#m_$name').val( inst.selectedMonth+1);
				   $('#y_$name').val( inst.selectedYear);
			   }
			, dateFormat: 'd.m.yy' });
			
			$('#d_$name').change(function(){
				var date=$('#d_$name').val()+'.'+$('#m_$name').val()+'.'+$('#y_$name').val();
				$('#$name').datepicker( 'setDate' , date );				
			});
			
			$('#m_$name').change(function(){
				var date=$('#d_$name').val()+'.'+$('#m_$name').val()+'.'+$('#y_$name').val();
				$('#$name').datepicker( 'setDate' , date );
				/*$.ajax({
				  url: '$url',
				  type: 'POST',				  
				  data: 'day='+$('#d_$name').val()+'&month='+$('#m_$name').val()+'&year='+$('#y_$name').val(),
				  success: function(data) {
				    $('#d_$name').html(data);
				  }
				});*/
				var daynum=daynums[$(this).val()-1];
				for(var i=27;i<31;i++)
					$('#d_$name').find('option').eq(i).css('display',i>daynum-1?'none':'');
			});
			
			$('#y_$name').change(function(){
				var date=$('#d_$name').val()+'.'+$('#m_$name').val()+'.'+$('#y_$name').val();
				$('#$name').datepicker( 'setDate' , date );
			});";
		if ($have_check == 1)
			$script .= "
			$('#c_$name').click(function(){
				var checked=!$('#c_$name').is(':checked');
				$('#m_$name').attr('disabled',checked);
				$('#d_$name').attr('disabled',checked);
				$('#y_$name').attr('disabled',checked);
				$('#$name').attr('disabled',checked);
				if(!checked)
				{
					var date=$('#d_$name').val()+'.'+$('#m_$name').val()+'.'+$('#y_$name').val();
					$('#$name').datepicker( 'setDate' , date );
					var daynum=daynums[$(this).val()-1];
					for(var i=27;i<31;i++)
						$('#d_$name').find('option').eq(i).css('display',i>daynum-1?'none':'');
				}				
			});		
			";
		$script .= "		
		});";
		$controller->view->headScript ()->appendScript ( $script, $type = 'text/javascript' );
		
		//TẠO GIAO DIỆN
		//check box
		if ($have_check == 1)
			$result .= "<input title='Check vào để sử dụng ngày tháng' type='checkbox' name='c_$name' id='c_$name' class='calendar c' " . ($c == 1 ? "checked='checked'" : "") . " value='1'/>";		
		//hộp chọn ngày
		$result .= "<select id='d_$name' class='calendar d' " . ($c == 1 ? "" : "disabled='disabled'") . " name='d_$name'>";
		if ($have_empty_option == 1)
			$result .= "<option value='0'>- Chọn -</option>";
		for($j = 1; $j <= 31; $j ++)
		{
			$selected = ($d == $j ? "selected='selected'" : "");
			$result .= "<option value='$j' $selected>$j</option>";
		}
		$result .= "</select> ";
		//hộp chọn tháng
		$result .= "<select id='m_$name' class='calendar m' " . ($c == 1 ? "" : "disabled='disabled'") . " name='m_$name'>";
		if ($have_empty_option == 1)
			$result .= "<option value='0'>- Chọn -</option>";
		for($j = 1; $j <= 12; $j ++)
		{
			$selected = ($m == $j ? "selected='selected'" : "");
			$result .= "<option value='$j' $selected>$j</option>";
		}
		$result .= "</select> ";
		//hộp chọn năm				
		$result .= "<select id='y_$name' class='calendar Y' " . ($c == 1 ? "" : "disabled='disabled'") . " name='y_$name'>";
		if ($have_empty_option == 1)
			$result .= "<option value='0'>- Chọn -</option>";
		for($j = $from_year; $j <= $to_year; $j ++)
		{
			$selected = ($y == $j ? "selected='selected'" : "");
			$result .= "<option value='$j' $selected>$j</option>";
		}
		$result .= "</select> ";
		
		//trả kết quả
		return $result;
	}
}
